package com.bawei.module_mine.ui

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityGoldBinding
import com.bawei.module_mine.http.intent.LoginIntent
import com.bawei.module_mine.http.state.LoginState
import com.bawei.module_mine.http.viewModel.LoginViewModel
import com.bawei.module_mine.model.AddAccountModel
import com.bawei.module_mine.model.GoldTransaction
import com.bawei.module_mine.model.TransactionType
import com.bawei.module_mine.adapter.GoldTransactionAdapter
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/mine/GoldActivity")
class GoldActivity : BaseActivity() {
    private lateinit var viewModel: LoginViewModel
    private lateinit var transactionAdapter: GoldTransactionAdapter
    private val binding by lazy {
        ActivityGoldBinding.inflate(layoutInflater)
    }

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun initView() {
        super.initView()
        // 初始化ViewModel
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]
        
        // 初始化适配器
        initAdapter()
        
        // 获取账户ID并请求数据
        loadAccountData()
        
        setupClickListeners()
    }
    
    private fun loadAccountData() {
        val accountId = AuthMMKV.accountId
        lifecycleScope.launch {
            viewModel.intents.send(LoginIntent.FindAccountById(accountId))
        }
    }

    override fun initData() {
        super.initData()
        // 监听状态变化
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.state.collect { state ->
                    when (state) {
                        is LoginState.AddAccountSuccess -> {
                            // 处理账户数据
                            updateGoldData(state.data)
                        }
                        is LoginState.Error -> {
                            Toast.makeText(this@GoldActivity, state.error, Toast.LENGTH_SHORT).show()
                            // 显示默认数据
                            updateGoldData(null)
                        }
                        LoginState.Idle -> {
                            // 空闲状态，可以显示加载动画
                        }
                        LoginState.Loading -> {
                            // 显示加载状态
                            showLoading(true)
                        }
                        is LoginState.Success -> {
                            // 登录成功状态，这里不需要处理
                        }

                        is LoginState.LikeSuccess -> {}
                        is LoginState.MineSuccess -> TODO()
                        else->{}
                    }
                }
            }
        }
    }
    
    override fun onResume() {
        super.onResume()
        // 每次页面重新获得焦点时刷新数据
        loadAccountData()
    }

    private fun initAdapter() {
        transactionAdapter = GoldTransactionAdapter()
        // 这里可以设置RecyclerView，但由于我们的布局中没有RecyclerView，
        // 所以暂时注释掉，如果需要可以添加到布局中
        // binding.rvTransactions.layoutManager = LinearLayoutManager(this)
        // binding.rvTransactions.adapter = transactionAdapter
        
        // 加载模拟数据
        loadMockTransactionData()
    }

    private fun loadMockTransactionData() {
        val mockTransactions = listOf(
            GoldTransaction(
                id = 1,
                type = TransactionType.EARN,
                amount = AuthMMKV.homeMoney,
                description = "观看视频奖励",
                timestamp = "2024-01-15 14:30",
                iconRes = R.drawable.ic_video,
                colorRes = R.drawable.circle_green
            ),
            GoldTransaction(
                id = 2,
                type = TransactionType.EARN,
                amount = AuthMMKV.liveMoney,
                description = "分享获得奖励",
                timestamp = "2024-01-15 10:15",
                iconRes = R.drawable.ic_share,
                colorRes = R.drawable.circle_blue
            ),
            GoldTransaction(
                id = 3,
                type = TransactionType.SPEND,
                amount = 200,
                description = "兑换商品",
                timestamp = "2024-01-14 16:45",
                iconRes = R.drawable.ic_gift,
                colorRes = R.drawable.circle_red
            )
        )
        transactionAdapter.updateTransactions(mockTransactions)
    }

    private fun setupClickListeners() {
        // 充值按钮
        binding.btnRecharge.setOnClickListener {
            Toast.makeText(this, getString(R.string.recharge_developing), Toast.LENGTH_SHORT).show()
        }

        // 提现按钮
        binding.btnWithdraw.setOnClickListener {
            Toast.makeText(this, getString(R.string.withdraw_developing), Toast.LENGTH_SHORT).show()
        }

        // 兑换按钮
        binding.btnExchange.setOnClickListener {
            Toast.makeText(this, getString(R.string.exchange_developing), Toast.LENGTH_SHORT).show()
        }

        // 查看全部明细
        binding.btnViewAll.setOnClickListener {
            Toast.makeText(this, getString(R.string.view_all_details), Toast.LENGTH_SHORT).show()
        }

        // 金币图标点击 - 刷新数据
        binding.goldIcon.setOnClickListener {
            loadAccountData()
            Toast.makeText(this, "数据已刷新", Toast.LENGTH_SHORT).show()
        }
    }

    private fun updateGoldData(accountData: AddAccountModel?) {
        showLoading(false)
        val homeMoney = AuthMMKV.homeMoney
        val liveMoney = AuthMMKV.liveMoney
        if (accountData != null) {
            // 使用真实数据
            binding.goldAmount.text = formatNumber(accountData.accountamount)
            binding.goldValue.text = "≈ ¥${formatCurrency(accountData.accountamount * 0.001)}" // 假设1000金币=1元
            // 今日获得：显示今日通过滑动获得的奖励
            binding.todayEarned.text = "+${homeMoney + liveMoney} 金币"
            // 累计获得：显示账户总余额（包含今日获得的奖励）
            binding.totalEarned.text = formatNumber(accountData.accountamount)
        } else {
            // 使用默认数据
            binding.goldAmount.text = "0"
            binding.goldValue.text = "≈ ¥0.00"
            binding.todayEarned.text = "0"
            binding.totalEarned.text = "0"
        }
    }

    private fun showLoading(show: Boolean) {
        // 这里可以添加加载动画
        // 例如显示/隐藏ProgressBar
    }

    private fun formatNumber(number: Int): String {
        return String.format("%,d", number)
    }

    private fun formatCurrency(amount: Double): String {
        return String.format("%.2f", amount)
    }
}